package com.itheima02.Day09;

/**
 * @author 刘全
 * @date 2021/7/25
 */
public class MyArrayList<E> {
    private int size;
    private Object[] elementdata = {};

    public boolean add(E e) {
        if (size == elementdata.length) {
            grow();
        }
        elementdata[size++] = e;
        return true;
    }

    public void grow() {
        int newLength;
        if (elementdata.length == 0) {
            newLength = 10;
        } else {
            newLength = elementdata.length + elementdata.length >> 1;
        }
        Object[] newList = new Object[newLength];
        System.arraycopy(elementdata, 0, newList, 0, elementdata.length);
        elementdata = newList;
    }

    public int size() {
        return size;
    }

    public <E> E get(int index) {
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("索引" + index + "超出了范围");
        }
        return (E) elementdata[index];
    }

    public <E> boolean set(int index, E e) {
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("索引" + index + "超出了范围");
        }
        elementdata[index] = e;
        return true;
    }

    public <E> E remove(int index) {
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("索引" + index + "超出了范围");
        }
        int newLength = size - index - 1;
        System.arraycopy(elementdata, index + 1, elementdata, index, newLength);
        elementdata[--size] = null;
        return (E)elementdata[index];
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < size; i++) {
            if (i == size - 1) {
                sb.append(elementdata[i]);
            } else {
                sb.append(elementdata[i]).append(", ");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
